package com.stormkai.controller;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.stormkai.controller.dto.UserDTO;
import com.stormkai.controller.vo.UserVO;
import com.stormkai.error.BusinessException;
import com.stormkai.error.EnumBusinessError;
import com.stormkai.response.CommonReturnType;
import com.stormkai.service.UserService;
import com.stormkai.service.model.UserModel;
import com.stormkai.validator.ValidatorImpl;

import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("/user")
@Slf4j
@CrossOrigin(allowCredentials="true", allowedHeaders="*")
public class UserController extends BaseController {
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private HttpServletRequest request;
	
	
	
	@GetMapping("/get")
	public CommonReturnType getUser(@RequestParam("id") Integer id) throws BusinessException {
		UserModel userModel = userService.getUserById(id);
		if(userModel == null) {
			throw new BusinessException(EnumBusinessError.USER_NOT_EXIST);
		}
		return CommonReturnType.create(convertFromModel(userModel));
	}
	
	@PostMapping(value="/getAuthCode",consumes= {"application/x-www-form-urlencoded"})
	public CommonReturnType getAuthCode(@RequestParam("telephone") String telephone) {
		//生成验证码
		String authCode = RandomStringUtils.randomNumeric(6);
		/*Random random = new Random();
		int randomInt = random.nextInt(99999);
		log.info("randomInt={}",randomInt);
		randomInt += 10000;
		String code = String.valueOf(randomInt);*/
		
		/*int randomInt = (int)(Math.random()*9+1)*100000;
		String code = String.valueOf(randomInt);*/
		
		
		//将验证码绑定用户手机号，存入session中
		request.getSession().setAttribute(telephone, authCode);
		//request.getSession().setMaxInactiveInterval(10);
		
		//发送验证码
		log.info("验证码={}",authCode);
		
		//让发送的验证码一分钟后失效
		/*final Timer timer=new Timer();
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				request.getSession().removeAttribute("telephone");
				timer.cancel();
			}
		},60*1000);*/
		return CommonReturnType.create("验证码发送成功");
	}
	
	@PostMapping(value="/register",consumes= {"application/x-www-form-urlencoded"})
	public CommonReturnType register(UserDTO userDTO) throws BusinessException {
		String authCode = (String) request.getSession().getAttribute(userDTO.getTelephone());
		
		if(!StringUtils.equals(authCode, userDTO.getAuthCode())) {
			throw new BusinessException(EnumBusinessError.PARAMETER_VALIDATION_ERROR,"短信验证码不合法！");
		}
		
		//用户注册流程
		UserModel userModel = new UserModel();
		BeanUtils.copyProperties(userDTO, userModel);
		userModel.setRegisterMode("byPhone");
		
		userModel.setEncrptPassword(EncodeByMd5(userDTO.getPassword()));
		userService.register(userModel);
		
		return CommonReturnType.create(userModel);
	}
	
	@PostMapping(value="/login",consumes= {"application/x-www-form-urlencoded"})
	public CommonReturnType login(@RequestParam("telephone") String telephone, @RequestParam("password") String password) throws BusinessException {
		//入参校验
		if(StringUtils.isEmpty(telephone) || StringUtils.isEmpty(password)) {
			throw new BusinessException(EnumBusinessError.PARAMETER_VALIDATION_ERROR,"请输入正确的用户名或密码");
		}
		//用户登录服务
		UserModel userModel = userService.validateLogin(telephone, this.EncodeByMd5(password));
		
		this.request.getSession().setAttribute("IS_LOGIN", true);
		this.request.getSession().setAttribute("LOGIN_USER", userModel);
		return CommonReturnType.create(null);
	}
	
	
	
	private UserVO convertFromModel(UserModel userModel){
        if (userModel == null) {
            return null;
        }

        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(userModel,userVO);
        return userVO;
    }
	
	public String EncodeByMd5(String password) {
		String salt= "qwerty234567-=+hjgiorewj";
		String saltPassword=salt+"/"+password;
		String md5Password = DigestUtils.md5DigestAsHex(saltPassword.getBytes());
		return md5Password;
	}

}
